<?php namespace app\service\controller;
use think\Controller;
use think\Db;

/**
 * e签宝服务层
 */
class Esign extends Controller{
	
//	服务端API
	private $apiArr = [
		'getAccessToken'		=>		'/v1/oauth2/access_token?appId={appId}&secret={secret}&grantType=client_credentials',	//获取鉴权Token
		'getUploadUrl'			=>		'/v3/files/file-upload-url',					//获取文件上传地址
		'uploadUrl'				=>		'/',											//文件流上传方法
		'checkKeyword'			=>		'/v3/files/{fileId}/keyword-positions',			//检索文件关键字坐标
		'createFlowOneStep'		=>		'/v3/sign-flow/create-by-file',					//基于文件发起签署
	];
	
	private $appId = '7438999218';							//应用id
	private $secret = 'e55feb35f2890f3598e213f19f77316a';	//secret
//	private $url = 'https://openapi.esign.cn';				//url
	private $url = 'https://smlopenapi.esign.cn';			//url(沙箱)
	private $header = [];									//header参数
	private $accessToken = '';								//accessToken
//	private $esignCallbackUrl = 'http://47.111.76.224:9999/PM/UpdateSignResult';			//签署回调地址
	private $esignCallbackUrl = '';	//签署回调地址
	
	public function __construct($api = ''){
		parent::__construct();
		$this -> accessToken = $this -> getAccessToken();
		$this -> header = [
			'X-Tsign-Open-App-Id:'	.	$this -> appId,						//项目ID
			'Content-Type:'			.	'application/json;charset=UTF-8',	//application/json;charset=UTF-8
			'X-Tsign-Open-Token:'	.	$this -> accessToken,				//accessToken
		];
	}
	
	
	/**
	 * 发起签署
	 * @param	$api		api地址
	 * @param	$fileId		待签署文件id
	 * @param	$fileName	待签署文件名称
	 * @param	$accountId		乙方签署人id
	 * @param	$partBPos		乙方盖章区域
	 */
	public function createFlowOneStep($fileId = '', $fileName = '', $xy){
		
		$signFields = [];
//		法人电子章
		if( !empty($xy1) ){
			$signFields[]	=	
				[
					'platformSign'	=>	false,							//是否平台自动签署，默认false
					'signerAccount'	=>	[
						'signerAccountId'				=>	$xy1['account_id'],//用户id
					],
					'signfields'	=>	[								//签署方信息
						[
							'sealId'				=>	$xy1['seal_id'],//印章ID
							'autoExecute'			=>	true,			//是否自动执行，默认false（如果自动签署，必须设置为true）
							'fileId'				=>	$fileId,		//文件fileId
							'posBean'				=>[					//签署区位置信息 。signType为0时，本参数无效； signType为1时, 页码和XY坐标不能为空,；signType为2时, 页码和Y坐标不能为空
								'posPage'				=>	$xy1['page'],
								'posX'					=>	$xy1['left'],
								'posY'					=>	$xy1['right'],
							],
							'width'					=>	150
						],
					],
				];
		}
		
		$param = [
			'docs' => [
				[
					'fileId'	=>	$fileId,							//待签署文件id
					'fileName'	=>	$fileName,							//待签署文件名称
				]
			],
			'flowInfo'	=>	[
				'autoArchive'		=>	true,							//是否自动归档，默认false
				'autoInitiate'		=>	true,							//是否自动归档，默认false
				'businessScene'		=>	explode('.', $fileName)[0],		//文件主题
			],
			'signers'	=>	$signFields,
		];
		
//		p($xy0);
//		p($xy1);
//		p($xy2);
		p($param);die;
		$url = $this -> url . $this -> apiArr['createFlowOneStep'];
		
		$re = requestPost($url, json_encode($param), $this -> header);
		$re = json_decode($re, TRUE);
		return $re;
	}

	/**
	 * 检索文件关键字坐标
	 */
	public function checkKeyword($fileId = '', $keywords = []){
		$url = $this -> url . $this -> apiArr['checkKeyword'];
		$url = str_replace('{fileId}', $fileId, $url);
		
		$param['fileId'] = $fileId;
		$param['keywords'] = $keywords;
		
		
		$re = requestPost($url, json_encode($param), $this -> header);
		$re = json_decode($re, TRUE);
		return $re;
	}

	/**
	 * 文件流上传(pdf文件)
	 */
	public function uploadUrl($url = '', $filePath = ''){
		$header = [
			'Content-MD5:' . $this -> getContentBase64Md5($filePath),
			'Content-Type:application/pdf',
		];
		
		$data = file_get_contents($filePath);
	
		$re = requestPut($url, $data, $header);
		$re = json_decode($re, TRUE);
		return $re;
	}
	
	/**
	 * 获取文件上传地址
	 */
	public function getUploadUrl($filePath = '', $fileName = ''){
		$url = $this -> url . $this -> apiArr['getUploadUrl'];
		
		$param['contentMd5'] = $this -> getContentBase64Md5($filePath);
		$param['contentType'] = 'application/pdf';
		$param['fileName'] = $fileName;
		$param['fileSize'] = filesize($filePath);
		
		$re = requestPost($url, json_encode($param), $this -> header);
		$re = json_decode($re, TRUE);
		return $re;
	}
	
	/**
	 * 获取accessToken
	 */
	private function getAccessToken(){
		$accessToken = controller("service/Cache") -> getCache("esignAccessToken");
		$accessToken = null;
		if( !$accessToken || empty($accessToken) || is_null($accessToken) || $accessToken == 'null' ){
			$url = $this -> url . $this -> apiArr['getAccessToken'];
			$url = str_replace('{appId}', $this -> appId, $url);
			$url = str_replace('{secret}', $this -> secret, $url);
			$re = requestGet($url);
			$re = json_decode($re, TRUE);
			if($re['code'] != 0){
				$outArr['code'] = '50003';
				$outArr['info'] = $re['message'];
				returnResults($outArr);
			}
			$accessToken = $re['data']['token'];
			controller("service/Cache") -> setCache("esignAccessToken", "", $accessToken, 7000);
		}
		return $accessToken;
	}
	
	/**
	 * 获取文件md5值(二进制，128位)
	 */
	private function getContentBase64Md5($filePath){
		$file = file_get_contents($filePath);
	    $md5file = md5($file,true);
	    $contentBase64Md5 = base64_encode($md5file);
	    return $contentBase64Md5;
	}
}
